#!/bin/bash
#
# Description: Create a joblist to analyse multiple tiles using CellProfiler.
# 
# The MIT License (MIT)
# Copyright (c) 2014-2016, Bas G.L. Nelissen, UMC Utrecht, the Netherlands.
# 
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# 
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# 

# Variables
SCRIPTNAME="$(basename $0)"
DESCRIPTIONSHORT="Create a joblist to analyse multiple tiles using CellProfiler."
CPBIN="cellprofiler" # command to run CellProfiler
DEFAULT_HANDLER="" # default is empty [qsub]
DEPENDENCIES=("$CPBIN" "convert") # these scripts/binaries must be in your path: `command -v binary`
DEFAULT_OUTPUT_SUFFIX=".cellprofiler" # relative to input dir
QSUBARGS="" # leave empty. 
DEFAULT_QSUBNAME="$SCRIPTNAME"
DEFAULT_QSUBARGS="-l h_rt=04:00:00 -l h_vmem=36G" # Maximum values: rt=runtime HH:MM:SS vmem=GB 

# Cleanup stage
set -e
function cleanup {
  # things to do on exit
  printf ""
}
trap cleanup EXIT

# Errors go to stderr
err() {
  echo "${SCRIPTNAME} ERROR: $@" >&2
}

# Debug go to stdout
debug() {
  echo "DEBUG $(date +'%Y-%m-%d %H:%M:%S'): $@" >&1 # or >/dev/null
}

# usage message
usage() {
cat <<- EOF
$SCRIPTNAME --help for more information.
EOF
}

# version info
version() {
cat << EOF
slideToolkit 0.1 beta
($SCRIPTNAME is part of the slideToolkit)

The MIT License (MIT) <http://opensource.org/licenses/MIT>
Copyright (c) 2014-2016, Bas G.L. Nelissen, UMC Utrecht, the Netherlands.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

There is NO WARRANTY, to the extent permitted by law.

Written by Bas G.L. Nelissen | https://github.com/bglnelissen.
EOF
}


# help message
helpMessage() {
cat <<- EOF
${SCRIPTNAME}: ${DESCRIPTIONSHORT}

usage:
  $SCRIPTNAME -i <dirname> -p <pipeline> [options]

options:
  -i, --inputdir <dirname>     directory with tiles to analyse
  -p, --pipeline <pipeline>    CellProfiler pipeline

  [--output-suffix] <text>     suffix for output directory ("$DEFAULT_OUTPUT_SUFFIX")
  [--handler] <jobhandler>     specify the job handler
  [--mkdir-output] <dirname>   create output directory before running CellProfiler
  [--ignore-dependencies]      ignores all dependencies, but gives warning

qsub:
  [-N, --name] <text>          qsub job identification name ("$DEFAULT_QSUBNAME")
  [--qsub-args] <arguments>    qsub arguments ("$DEFAULT_QSUBARGS")

  --help                       display this help
  --version                    display version and license information


examples:
  $SCRIPTNAME -i "./" -p "pipeline.cp"

print a job list:
  find "\$(pwd)" -iname "*tiles" -not -path "*out*" -type d -exec "\$(command -v "$SCRIPTNAME")" -i "{}" -N "{}" --handler=qsub -p "pipeline.cp" --mkdir-output \;

dependencies: ${DEPENDENCIES[@]}

Create a joblist that analyses multiple folders containing tiles using
CellProfiler. CellProfiler results are stored in the output directory
and is located at the same path as the input directory with default
suffix: "$DEFAULT_OUTPUT_SUFFIX".
The output directory can be generated using the --mkdir-output flag,
some versions of CellProfiler want to output directory to exist before
starting the pipeline.
${SCRIPTNAME} expects "$CPBIN" to exist as a script that redirects
to your CellProfiler binairy.

The slideToolkit and all its tools are released under the terms of the MIT license.
The slideToolkit (C) 2014-2016, Bas G.L. Nelissen, UMC Utrecht, the Netherlands.
Report issues at https://github.com/bglnelissen/slideToolkit/issues.

EOF
}

# Menu
# Empty variables
INPUTDIR=""
PIPELINE=""
NAME=""
QSUBNAME=""
QSUBARGS=""
HANDLER=""
# illegal option
illegalOption() {
cat <<- EOF
$SCRIPTNAME: illegal option $1
$(usage)
EOF
exit 1
}
# loop through options
while :
do
  case $1 in
      -h)
      usage
      exit 0 ;;
    --help | -\?)
      helpMessage
      exit 0 ;;
    --version )
      version
      exit 0 ;;
    --handler=*)
      HANDLER=${1#*=}
      shift ;;
    --handler)
      HANDLER=$2
      shift 2 ;;
    -i | --inputdir)
      INPUTDIR=$2
      shift 2 ;;
    --inputdir=*)
      INPUTDIR=${1#*=}
      shift ;;
    -p | --pipeline)
      PIPELINE=$2
      shift 2 ;;
    --pipeline=*)
      PIPELINE=${1#*=}
      shift ;;
    --output-suffix=*)
      DEFAULT_OUTPUT_SUFFIX=${1#*=}
      shift ;;
    --mkdir-output)
      MKDIR_OUTPUT="MKDIR_OUTPUT"
      shift ;;
    -N | --name)
      QSUBNAME=$2
      shift 2 ;;
    --qsub-args)
      QSUBARGS=$2
      shift 2 ;;
     --ignore-dependencies)
      IGNOREDEPENDENCIES=TRUE
      shift ;;
    --) # End of all options
      shift
      break ;;
    -*)
      illegalOption "$1"
      shift ;;
    *)  # no more options. Stop while loop
      break ;;
  esac
done

# DEFAULTS
# set FILE default
if [ "$INPUTDIR" != "" ]; then
  INPUTDIR="$INPUTDIR"
fi
# set LAYER default
if [ "$PIPELINE" != "" ]; then
  PIPELINE="$PIPELINE"
fi
# set LAYER default
if [ "$DEFAULT_OUTPUT_SUFFIX" != "" ]; then
  DEFAULT_OUTPUT_SUFFIX="$DEFAULT_OUTPUT_SUFFIX"
fi
# set QSUBNAME default
if [ "$QSUBNAME" != "" ]; then
  QSUBNAME="$QSUBNAME"
else
  QSUBNAME="$DEFAULT_QSUBNAME"
fi
# set QSUBARGS default
if [ "$QSUBARGS" != "" ]; then
  QSUBARGS="$QSUBARGS"
else
  QSUBARGS="$DEFAULT_QSUBARGS"
fi
# set HANDLER
if [ "$HANDLER" != "" ]; then
  HANDLER="$HANDLER"
else
  HANDLER="$DEFAULT_HANDLER"
fi
# set IGNOREDEPENDENCIES
if [[ "$IGNOREDEPENDENCIES" =~ (true|TRUE|YES|yes) ]] ; then
  IGNOREDEPENDENCIES=true
else
  IGNOREDEPENDENCIES=false
fi

# requirements
checkRequirements() {
  # input dir must exist
  if ! [[ -d "$INPUTDIR" ]] ; then
    err "No such inputdir: $INPUTDIR"
    usage
    exit 1
  fi
  # pipeline must exist
  if ! [[ -f "$PIPELINE" ]] ; then
    err "No such pipeline: $PIPELINE"
    usage
    exit 1
  fi
  # set HANDLER (parallel|qsub|etc)
  if ! [[ "$HANDLER" =~ (qsub|QSUB) || "$HANDLER" == "" ]] ; then
    err "No such job handler: $HANDLER"
    usage
    exit 1
  fi
}

# Dependencies
checkDependencies(){
  DEPS=""
  DEPS_FAIL="0"
  for DEP in ${DEPENDENCIES[@]}; do
    if [[ 0 != "$(command -v "$DEP" >/dev/null ;echo "$?")" ]]; then
       err "Missing dependency: $DEP"
       DEPS_FAIL=$(($DEPS_FAIL + 1))
    fi
  done
  if [[ "$DEPS_FAIL" > 0 ]]; then
    err "Fix missing dependencies (${DEPS_FAIL})"
    helpMessage
    exit 1
  fi
}

# actual program
programOutput(){
  # set variables
  CPBINFULL="$(command -v "$CPBIN" )" # full path
  PIPELINEFULL="$(echo "$(cd "$(dirname "$PIPELINE")"; pwd)"/"$(basename "$PIPELINE")")" # full path to pipeline
  INPUTDIRFULL="$(echo "$(cd "$(dirname "$INPUTDIR")"; pwd)"/"$(basename "$INPUTDIR")")" # full path to dir with Tiles
  OUTPUTDIRFULL="$INPUTDIRFULL""$DEFAULT_OUTPUT_SUFFIX""/" # full path to output dir
  QSUBNAME=$(echo "$QSUBNAME" | perl -p -e 's/.*\/(.+)/\1/g' | perl -p -e 's/[^0-9a-zA-Z]*//g') # [a-zA-Z0-9] only
  MKDIR="mkdir -p \"$OUTPUTDIRFULL\""
  
  if [[  "$HANDLER" == "qsub"  ]]; then
    # create job command for qsub
    JOB="qsub -N \"${QSUBNAME}\" $QSUBARGS $CPBINFULL -r -c -i $INPUTDIRFULL -o $OUTPUTDIRFULL -p $PIPELINEFULL" 
  elif [[  "$HANDLER" == ""  ]]; then
    # create job command
    JOB="$CPBINFULL -r -c -i $INPUTDIRFULL -o $OUTPUTDIRFULL -p $PIPELINEFULL" 
  fi
  # echo output back to user, give mkdir command if this option was set.
  if [[ "$MKDIR_OUTPUT" == "MKDIR_OUTPUT" ]] ; then
    echo "$MKDIR" " && " "$JOB"
  else
    echo "$JOB"
  fi
}

# all check?
checkRequirements
checkDependencies

# lets go!
programOutput
